import { ContactContext } from "./context";
import { useContext, useEffect, useState } from "react";
import "./ContactDetail.css";
import { baseSteps } from "./baseSteps";

const ContactDetail = (props) => {
    const { contactItems, currentItemIndex, setState } = useContext(ContactContext);
    const [cls, setCls] = useState("contact-detail out");
    const [typedInText, setTypedInText] = useState("");
    const [inprocessClick, setInprogressClick] = useState(false);
    const [justHired, setJustHired] = useState(false);

    const [statusCls, setStatusCls] = useState("");
    const { page } = useContext(ContactContext);
    useEffect(() => {
        if (page === "ContactDetail") {
            setCls("contact-detail");
        }
        if (page === "Contacts") {
            setCls("contact-detail out");
        }
    }, [page])


    if (currentItemIndex < 0) {
        return <div className={cls}></div>;
    }
    const item = contactItems[currentItemIndex];
    if (!item) {
        return <div className={cls}></div>;
    }

    const updateState = (newItem) => {
        const newItems = [...contactItems];
        newItems.splice(currentItemIndex, 1, newItem)
        setState({ contactItems: newItems })
    }
    const { name, isNew, email, phone, step, callClicked, askedQuestion } = item;

    const handleBackClick = () => {
        if (callClicked) {
            const newItem = Object.assign({}, contactItems[currentItemIndex], { callClicked: false });
            updateState(newItem);
            return;
        }
        setState({ page: "Contacts" });
        setTypedInText("");
    };

    const handleCallIconClick = () => {
        if (step !== 1) {
            return;
        }
        const newItem = Object.assign({}, contactItems[currentItemIndex], { callClicked: true });
        updateState(newItem);
    };

    const handleTextareaChange = (e) => {
        const v = e.target.value;
        setTypedInText(v);
    }

    const handleLogClick = () => {
        if (step !== 1 || !typedInText || !typedInText.trim()) {
            return;
        }
        const newItem = Object.assign({}, contactItems[currentItemIndex], { callClicked: false, askedQuestion: typedInText, step: 2 });
        updateState(newItem);
    }

    const handlePageClick = () => {
        if (step !== 2) {
            return;
        }
        setStatusCls("flashing");
        setTimeout(() => {
            setStatusCls("");
        }, 1000);
    }

    const handleStatusClick = (e) => {
        e.stopPropagation();
        e.preventDefault();
        if (step !== 2) {
            return;
        }
        setInprogressClick(true);
    }

    const cancelStatusAction = () => {
        setInprogressClick(false);
    }

    const handleHireClick = () => {
        if (step !== 2) {
            return;
        }
        const newItem = Object.assign({}, contactItems[currentItemIndex], { step: 3 });
        updateState(newItem);
        setJustHired(true);
        setTimeout(() => {
            setJustHired(false);
        }, 900);
    }

    const fadeOut = callClicked ? "fade-out" : "";
    const status = baseSteps[step].status;
    const steps = baseSteps.map((s, i) => {
        return i <= step ? s : null;
    }).filter(s => s).reverse();

    let short = "";


    const logCallContentCls = callClicked ? "fade-move-in" : "";

    let content = <div className={`detail-content`} onClick={handlePageClick}>
        <div className={`user-info-action ${fadeOut}`}>
            <div className={`user-info ${fadeOut}`}>
                <img src="/imgs/14.png" alt="14" />
                <div>
                    <div className="username">
                        <div className="name">{name}</div>
                        {isNew && <div className="is-new">New</div>}
                    </div>
                    <div className="status-block">
                        {status && <span onClick={handleStatusClick} className={`status status${step} ${statusCls}`}>{status}</span>}
                    </div>
                </div>
            </div>
            <div className={`action ${fadeOut}`}>
                <div className="call-block">
                    <img className="call" onClick={handleCallIconClick} src={"/imgs/3.png"} alt="3" />
                    <span>Log Call</span>
                </div>
                <img className="action-img" src="/imgs/4.png" alt="4" />
                <img className="action-img" src="/imgs/5.png" alt="5" />
                <img className="action-img" src="/imgs/6.png" alt="6" />
                <img className="action-img" src="/imgs/7.png" alt="7" />
            </div>
        </div>
        <div className={`contact-detail-block ${fadeOut}`}>
            <div className="title">Contact Detail
            <div className="edit-btn" onClick={handleCallIconClick}>Edit</div></div>
            <div className="content">
                <div className="row">
                    <div className="name">Email</div>
                    <div className="value">{email}</div>
                </div>
                <div className="row">
                    <div className="name">Phone</div>
                    <div className="value">{phone}</div>
                </div>
            </div>
        </div>
        <div className={`activities ${fadeOut}`}>
            <div className="title">Activities</div>
            <div className={`content ${steps.length > 2 ? "shadow" : ""}`}>
                {
                    steps.map((s, index) => {
                        let { icon, text, time, desc, stepIndex } = s;
                        if (stepIndex === 2 && askedQuestion) {
                            desc = askedQuestion;
                        }
                        let hiredCls = "";
                        if (justHired) {
                            if (stepIndex === 3) {
                                hiredCls = "fade-in";
                            } else {
                                hiredCls = "move-down"
                            }
                        }
                        short = desc ? "" : "short";

                        const res = <div className={`row ${hiredCls}`} key={text}>
                            <div className="icon-wrapper">
                                <img className={`icon`} src={icon} alt={icon} />
                                {index < steps.length - 1 && <div className={`line ${short}`}></div>}
                            </div>
                            <div className="info">
                                <div className="text">{text}</div>
                                <div className="info-time">{time}</div>
                                <div className="desc">{desc}</div>
                            </div>
                        </div>
                        return res;
                    })
                }
            </div>
            <div className={`call-detail-title ${logCallContentCls}`}>Call Detail</div>
            <div className={`call-content  ${logCallContentCls}`}></div>
            <textarea className={`call-text  ${logCallContentCls}`} onChange={handleTextareaChange} placeholder="What have you discussed?" value={typedInText}>{typedInText}</textarea>
            <span className={`time ${logCallContentCls}`}>{new Date().toLocaleString("en").replace(",", "")}</span>
            <span className={`log ${typedInText ? 'active' : ""}`} onClick={handleLogClick}>Log</span>
            <div></div>
        </div>
    </div>

    return <>
        <div className={cls}>
            <div className="header">
                <div className="content">
                    <div className="title">
                        <img onClick={handleBackClick} className="back" src="/imgs/13.png" alt="12" />
                        {name}
                    </div>
                </div>
            </div>
            {content}
        </div>
        <div className={`status-actions-mask ${inprocessClick ? "fade-in" : ""}`} onClick={cancelStatusAction}>
            <div className="status-actions-pannel">
                <div className="status-action">
                    <div className="item" onClick={handleHireClick}>Make as Hired</div>
                    <div className="item">Follow Up</div>
                </div>
                <div className="cancel" onClick={cancelStatusAction}>Cancel</div>
            </div>
        </div>
    </>
}

export default ContactDetail;